<template>
	<el-dialog :title="titleMap[mode]" v-model="visible" width="80%" destroy-on-close @closed="$emit('closed')" align-center>
        <el-container>
            <el-main>
                <el-form :model="form" :rules="rules" :disabled="mode == 'show'" ref="dialogForm" label-width="110px" label-position="right" style="height:650px;overflow:auto">
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="合同号" prop="contract_no">
                                <el-input v-model="form.contract_no" placeholder="请输入合同号" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="工厂货号" prop="factory_number" >
                                <el-input v-model="form.factory_number" placeholder="请出入工厂货号" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="批次号" prop="batch_number">
                                <el-input v-model="form.batch_number" placeholder="请输入批次号" readonly></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="客户名称" prop="custom_name">
                                <el-input v-model="form.custom_name" readonly></el-input>
                                <!-- <el-select v-model="form.style_id" clearable style="width: 100%" placeholder="请选择">
                                    <el-option v-for="item in curList" :key="item.custom_id" :label="item.apply_name" :value="item.custom_id" />
                                </el-select> -->
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="生产工序" prop="produce_process">
                                <el-select v-model="form.produce_process" clearable style="width: 100%" placeholder="请选择" @change="proProcess">
                                    <el-option label="织机" value="1" />
                                    <el-option label="织机+缝挑" value="2" />
                                    <el-option label="织机+缝挑+后整" value="3" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="承制人" prop="supplier_id">
                                <el-select v-model="form.supplier_id" clearable style="width: 100%" placeholder="请选择">
                                    <el-option v-for="item in SupplierList" :key="item.apply_id" :label="item.referred_as" :value="item.apply_id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                            <el-form-item label="客户订单号" prop="order_no" >
                                <el-input v-model="form.order_no" placeholder="请输入客户订单号" readonly></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="单价" prop="price" >
                                <el-input v-model="form.price" placeholder="请输入单价" ></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="单位" prop="unit">
                                <el-select v-model="form.unit" clearable style="width: 100%" placeholder="请选择" @change="proProcess">
                                    <el-option label="员/打" value="1" />
                                    <el-option label="员/件" value="2" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="针种" prop="needle_seed">
                                <el-select v-model="form.needle_seed" clearable style="width: 100%" filterable placeholder="请选择">
                                    <el-option v-for="item in needleList" :key="item.id" :label="item.title" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="6">
                             <el-form-item label="要求完成日期" prop="due_date" >
                                <el-date-picker v-model="form.due_date" :value-format="'YYYY-MM-DD'" @change="timeChange" style="width:100%" type="date" placeholder="请选择要求完成时间" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="要求首次交期" prop="first_delivery_date" >
                                <el-date-picker v-model="form.first_delivery_date" :value-format="'YYYY-MM-DD'" style="width:100%" type="date" placeholder="请选择要求首次交间" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="备注" prop="remark">
                                <el-input v-model="form.remark" placeholder="请输入备注"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <!-- 订单明细 -->
                    <el-col :span="24">
                        <el-form-item label="订单明细" prop="size_data">
                            <sc-form-table ref="table" v-model="form.size_data" :addTemplate="addTemplate" placeholder="暂无数据" hideAdd hideDelete>
                                <el-table-column prop="size" label="尺码" width="100" align="center"></el-table-column>
                                <el-table-column prop="produce_num" label="生产单数量" width="120" align="center"></el-table-column>
                                <el-table-column prop="pending_num" label="待缝挑数量" width="180" align="center"></el-table-column>
                                <el-table-column prop="weaving_num" label="缝挑数量" width="180" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.weaving_num" @input="input(scope.row)" placeholder="请输入缝挑数量"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="weight" label="克重" width="180" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.weight" @input="input(scope.row)" placeholder="请输入克重"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="total_weight" label="码数总重量/KG" width="180" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.total_weight"  placeholder="请输入码数总重量"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="loom_time" label="织机时间" width="180" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.loom_time" @input="input(scope.row)" placeholder="请输入织机时间"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="machine_num" label="所需机台" width="180" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.machine_num"  placeholder="请输入"></el-input>
                                    </template>
                                </el-table-column>
                            </sc-form-table>
                        </el-form-item>
                    </el-col>
                    <!-- 毛料明细 -->
                    <el-col :span="24">
                        <el-form-item label="毛料明细" prop="material_data">
                            <sc-form-table ref="table" v-model="form.material_data" :addTemplate="addTemplate" placeholder="暂无数据" hideAdd hideDelete>
                                <el-table-column prop="material_name" label="毛料名称" align="center"></el-table-column>
                                <el-table-column prop="material_spec_code" label="毛料编码" align="center"></el-table-column>
                                <el-table-column prop="colour" label="颜色" align="center"></el-table-column>
                                <el-table-column prop="color_number" label="色号" align="center"></el-table-column>
                                <el-table-column prop="ratio" label="比例" align="center"></el-table-column>
                                <el-table-column prop="loss_ratio" label="损耗" align="center"></el-table-column>
                                <el-table-column prop="total_weight" label="所需重量" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.total_weight" placeholder="请输入实发重量" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="batch_number" label="缸号" align="center">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.batch_number" clearable style="width: 100%" placeholder="请选择">
                                            <el-option v-for="item in scope.row.batch_stock" :key="item.batch_no" :label="item.batch_no" :value="item.batch_no" />
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column width="75" align="center">
                                    <template #default="scope">
                                        <el-button type="primary" size="small" @click="count(scope.row)">计算</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="reality_weight" label="实发重量" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.reality_weight" @input="input(scope.row)" placeholder="请输入实发重量"></el-input>
                                    </template>
                                </el-table-column>
                            </sc-form-table>
                        </el-form-item>
                    </el-col>
                    <!-- 辅料明细 -->
                    <el-col :span="24">
                        <el-form-item label="辅料明细" prop="accessories_data">
                            <sc-form-table ref="table" v-model="form.accessories_data" :addTemplate="addTemplate" placeholder="暂无数据" hideAdd hideDelete>
                                <el-table-column prop="material_name" label="毛料名称" align="center"></el-table-column>
                                <el-table-column prop="material_spec_code" label="毛料编码" align="center"></el-table-column>
                                <el-table-column prop="colour" label="颜色" align="center"></el-table-column>
                                <el-table-column prop="color_number" label="色号" align="center"></el-table-column>
                                <el-table-column prop="ratio" label="用量" align="center"></el-table-column>
                                <el-table-column prop="loss_ratio" label="损耗" align="center"></el-table-column>
                                <el-table-column prop="total_weight" label="所需数量" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.total_weight" placeholder="请输入实发数量" readonly></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="batch_number" label="缸号" align="center">
                                    <template #default="scope">
                                        <el-select v-model="scope.row.batch_number" clearable style="width: 100%" placeholder="请选择">
                                            <el-option v-for="item in scope.row.batch_stock" :key="item.batch_no" :label="item.batch_no" :value="item.batch_no" />
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column width="75" align="center">
                                    <template #default="scope">
                                        <el-button type="primary" size="small" @click="couns(scope.row)">计算</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="reality_weight" label="实发数量" align="center">
                                    <template #default="scope">
                                        <el-input v-model="scope.row.reality_weight" @input="input(scope.row)" placeholder="请输入实发数量"></el-input>
                                    </template>
                                </el-table-column>
                            </sc-form-table>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-main>
            <el-footer>
                <div style="display:flex;justify-content: end;">
                    <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保存并审核</el-button>
                    <el-button :loading="isSaveing" @click="submit()">保存</el-button>
                    <el-button @click="visible=false" >取消</el-button>
                </div>
            </el-footer>
        </el-container>
	</el-dialog>
</template>

<script>
	export default {
		emits: ['success', 'closed'],
		data() {
			return {
				mode: "add",
				titleMap: {
					add: '新增委外合同单',
					edit: '修改生产任务',
					show: '查看'
				},
                dialog: {
				    save: false,
			    },
				visible: false,
				isSaveing: false,
                grade:"潜力",
				//表单数据
				form: {
					id:"",
                    contract_no:"",
					produce_no: "",
                    order_no: "",
                    batch_number:"",
                    price: "",
                    unit: "",
                    supplier_id:"",
                    produce_process:"",
                    needle_seed:"",
                    due_date:"",
                    first_delivery_date:"",
                    remark:"",
                    size_data:[],   //缝挑信息
                    material_data:[], //毛料信息
                    accessories_data:[], //辅料信息
                    process_id:8,
				},
                size:[],
				//验证规则
				rules: {
                    produce_process: [
                        {required: true, message: '请选择生产工序'}
                    ],
                    supplier_id: [
                        {required: true, message: '请选择承制人'}
                    ],
                    price: [
                        {required: true, message: '请输入单价'}
                    ],
                    unit: [
                        {required: true, message: '请输入单位'}
                    ],
                    due_date: [
                        {required: true, message: '请选择日期'}
                    ],
                    first_delivery_date: [
                        {required: true, message: '请选择日期'}
                    ],
				},
				goodsList: [],  //商品款式
                curList:[],//客户
                needleList:[],//针种
                woolList:[],//毛种
                humList:[],//员工
                SupplierList:[],//承制人
                checkDay:"",//选择时间距今时间
                allWeight:"",//总重量
                allNum:"",//总数量
			}
		},
		mounted() {
            this.getCustomerList()
            this.getNeedle()
            this.getHum()
		},
		methods: {
            paperUpload() {
                // 下载文件
                const fileUrl = this.form.paper_sample_url;
                const link = document.createElement("a");
                link.href = fileUrl;
                link.download = this.form.paper_sample_url;
                link.click();
            },
            ziliaoUpload() {
                // 下载文件
                const fileUrl = this.form.ziliao_url;
                const link = document.createElement("a");
                link.href = fileUrl;
                link.download = this.form.ziliao_url;
                link.click();
            },
			//显示
			open(mode='add'){
				this.mode = mode;
				this.visible = true;
				return this
			},
			//表单提交方法
			submit(){
                console.log('this.form :>> ', this.form);
				this.$refs.dialogForm.validate(async (valid) => {
					if (valid) {
						this.isSaveing = true;
						var res  = [];
						res = await this.$API.produce.contract.createContract.post(this.form);
						this.isSaveing = false;
						if(res.code == 1){
							this.$emit('success', this.form, this.mode)
							this.visible = false;
							this.$message.success("操作成功")
						}else{
							this.$alert(res.message, "提示", {type: 'error'})
						}
					}else{
						return false;
					}
				})
			},
			//表单注入数据
			async setData(data){
                this.form.id = data.id
                var res = await this.$API.produce.getProduce.detail.get({id:data.id});
                this.form.contract_no = res.data.contract_no
                this.form.factory_number = res.data.factory_number
                this.form.produce_no = res.data.produce_no
                this.form.order_no = res.data.order_no
                this.form.custom_name = res.data.custom_name
                this.form.batch_number = res.data.batch_number
                this.form.needle_seed = res.data.needle_seed
                this.form.remark = res.data.remark
                let orderDetail = []
                res.data.orderDetail.map(item=>{
                    let detail = {
                        size:item.goods_size,
                        num:item.num,
                        produce_num:item.produce_num,
                        weight:item.weight,
                        total_weight:item.total_weight,
                        loom_time:"",
                        pending_num:item.pending_num,
                        weaving_num:item.weaving_num,
                    }
                    res.data.goods.gross_weight.map(item1=>{
                        if(item.goods_size==item1.size){
                            detail.loom_time = item1.loom_time
                        }
                    })
                    orderDetail.push(detail)
                })
                // 订单明细size_data
                this.form.size_data = orderDetail
                // 毛料明细
                let material  =[]
                res.data.material_data.map(item=>{
                    let detail = {
                        material_name:item.material_name,//毛料名称
                        material_spec_code:item.material_spec_code,//毛料编码
                        colour:item.materialSpec.colour,//毛料颜色
                        color_number:item.materialSpec.color_number,//毛料色号
                        ratio:item.ratio,//比例
                        loss_ratio:item.loss_ratio,//损耗
                        material_id:item.material_id,//毛料ID
                        total_weight:"",//所需重量
                        reality_weight:"",//实发重量
                        batch_number:"",//缸号
                        batch_stock:item.batch_stock
                    }
                     material.push(detail)
                })
                this.form.material_data = material
                // 物料明细
                let accessories  =[]
                res.data.accessories_data.map(item=>{
                    let detail = {
                        material_name:item.material_name,//辅料名称
                        material_spec_code:item.material_spec_code,//辅料编码
                        colour:item.materialSpec.colour,//辅料颜色
                        color_number:item.materialSpec.color_number,//辅料色号
                        ratio:item.ratio,//用量
                        loss_ratio:item.loss_ratio,//损耗
                        material_id:item.material_id,//辅料ID
                        total_weight:"",//所需重量
                        reality_weight:"",//实发重量
                        batch_number:"",//缸号
                        batch_stock:item.batch_stock
                    }
                     accessories.push(detail)
                })
                this.form.accessories_data = accessories
			},
            // 获取客户
            async getCustomerList(){
				var res = await this.$API.all.customer.get();
				this.curList = res.data;
			},
            //所有针种
            async getNeedle(){
                var res = await this.$API.all.needle.get();
                this.needleList = res.data;
            },
            // 跟单人
            async getHum(){
                var res = await this.$API.all.staff.get();
                this.humList = res.data;
            },
            // 切换生产工序,获取承制人
            async proProcess(e){
                var res = await this.$API.produce.contract.getSupplierList.get({produce_process:e});
                console.log('res :>> ', res);
                this.SupplierList = res.data
            },
            input(row){
                row.total_weight = (Number(row.weaving_num) * Number(row.weight)/1000).toFixed(2);
                row.machine_num = (Number(row.loom_time * row.weaving_num) / Number(this.checkDay * 1320)).toFixed(0)
                let t = 0;
                let y = 0
                for (let i = 0; i < this.form.size_data.length; i++) {
                    t = Number(this.form.size_data[i].total_weight) + t;
                    y = Number(this.form.size_data[i].weaving_num) + y;
                }
                this.allWeight = t;
                this.allNum = y;
            },
            timeChange(){
                // 获取选择的日期
                const selectedDate = new Date(this.form.due_date);
                // 获取当前日期
                const currentDate = new Date();
                // 计算天数差值
                const timeDiff = selectedDate.getTime() - currentDate.getTime();
                const daysDiff = Math.ceil(timeDiff / (1000 * 3600 * 24));
                this.checkDay = daysDiff
            },
            count(row){
                console.log(row);
                row.total_weight = (this.allWeight * (row.ratio/100) * (1+row.loss_ratio/100)).toFixed(2)
            },
            couns(row){
                console.log(row);
                row.total_weight = (this.allNum * row.ratio * (1+row.loss_ratio/100)).toFixed(0)
                // row.total_weight = Math.ceil(this.allNum * row.ratio * (1+row.loss_ratio/100))   //向上取整
            },
		}
	}
</script>

<style lang="scss"></style>
